package com.example.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.domain.entity.Device;
import com.example.domain.entity.Provider;
import com.example.domain.entity.ProviderComplaint;
import com.example.domain.query.DeviceQuery;
import com.example.domain.query.ProviderQuery;
import com.example.mapper.ProviderComplaintMapper;
import com.example.mapper.ProviderMapper;
import com.example.service.IProviderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author baomidou
 * @since 2025-05-13
 */
@Service
public class ProviderServiceImpl extends ServiceImpl<ProviderMapper, Provider> implements IProviderService {
    @Autowired
    private ProviderComplaintMapper providerComplaintMapper;

    @Override
    public IPage<Provider> pageQuery(ProviderQuery query, int pageNum, int pageSize) {
        Page<Provider> page = new Page<>(pageNum, pageSize);
        QueryWrapper<Provider> wrapper = new QueryWrapper<>();
        if (query != null) {
            if (query.getProviderId() != null) {
                wrapper.eq("provider_id", query.getProviderId());
            }
            if (StringUtils.hasText(query.getProviderName())) {
                wrapper.like("provider_name", query.getProviderName());
            }
            if (StringUtils.hasText(query.getFactoryAddress())) {
                wrapper.eq("factory_address", query.getFactoryAddress());
            }
            if (StringUtils.hasText(query.getPrincipalName())) {
                wrapper.eq("principal_name", query.getPrincipalName());
            }
            if (StringUtils.hasText(query.getPrincipalPhone())) {
                wrapper.eq("principal_phone", query.getPrincipalPhone());
            }
            if (query.getCompanyType() != null) {
                wrapper.eq("company_type", query.getCompanyType());
            }
            if (query.getRegisteredCapital() != null) {
                wrapper.eq("registered_capital", query.getRegisteredCapital());
            }
            if (query.getEmployeeCount() != null) {
                wrapper.eq("employee_count", query.getEmployeeCount());
            }
            if (query.getEstablishedYearStart() != null && query.getEstablishedYearEnd() != null) {
                wrapper.between("established_year", query.getEstablishedYearStart(), query.getEstablishedYearEnd());
            }
            if (StringUtils.hasText(query.getDescription())) {
                wrapper.eq("description", query.getDescription());
            }
            if (query.getAuditStatus() != null) {
                wrapper.eq("audit_status", query.getAuditStatus());
            }
            if (StringUtils.hasText(query.getDescription())) {
                wrapper.eq("rating", query.getRating());
            }
        }
        return this.page(page, wrapper);
    }

    @Override
    @Transactional
    public boolean audit(Integer providerId, Integer auditStatus, String auditComment, Integer auditorId) {
        Provider provider = getById(providerId);
        if (provider == null) {
            return false;
        }

        provider.setAuditStatus(auditStatus);
        provider.setAuditComment(auditComment);
        provider.setAuditorId(auditorId);
        provider.setAuditTime(LocalDateTime.now());

        // 如果是首次审核通过，设置默认评级为A
        if (auditStatus == 1 && provider.getRating() == null) {
            provider.setRating("A");
        }

        // 如果是首次审核，设置默认为启用状态
        if (provider.getIsActive() == null) {
            provider.setIsActive(true);
        }

        return updateById(provider);
    }

    @Override
    @Transactional
    public boolean submitComplaint(ProviderComplaint complaint) {
        // 设置投诉时间和初始状态
        complaint.setComplaintTime(LocalDateTime.now());
        complaint.setStatus(0); // 未处理

        return providerComplaintMapper.insert(complaint) > 0;
    }

    @Override
    @Transactional
    public boolean updateRating(Integer providerId, String rating, String reason, Integer operatorId) {
        // 更新供应商评级
        Provider provider = getById(providerId);
        if (provider == null) {
            return false;
        }
        provider.setRating(rating);

        // 更新对应投诉记录
        LambdaQueryWrapper<ProviderComplaint> complaintQuery = new LambdaQueryWrapper<>();
        complaintQuery.eq(ProviderComplaint::getProviderId, providerId)
                .eq(ProviderComplaint::getStatus, 0)
                .orderByDesc(ProviderComplaint::getComplaintTime)
                .last("LIMIT 1");

        ProviderComplaint latestComplaint = providerComplaintMapper.selectOne(complaintQuery);
        if (latestComplaint != null) {
            latestComplaint.setStatus(1);
            latestComplaint.setResult(reason);
            latestComplaint.setProcessTime(LocalDateTime.now());
            providerComplaintMapper.updateById(latestComplaint);
        }

        return updateById(provider) && latestComplaint != null;
    }

    @Override
    @Transactional
    public boolean toggleActive(Integer providerId, Boolean isActive) {
        Provider provider = getById(providerId);
        if (provider == null) {
            return false;
        }

        provider.setIsActive(isActive);

        return updateById(provider);
    }
}
